package com.heny.nc.service;

import com.heny.demo.common.CommonErrorCode;
import com.heny.demo.common.CommonException;
import com.heny.nc.model.NCModel;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author litao.cc
 * @version TxtProcessor.java v0.1 2025/4/26 18:44
 * @date 2025/4/26 18:44
 * @description 存为txt文件
 */
public class TxtProcessor extends AbstractSaveDataProcessor {
    @Override
    public List<String> save(Map<Integer, List<NCModel>> data, String path, String baseFileName) {
        System.out.println("TxtProcessor start");

        List<String> pathList = new ArrayList<>(data.size());
        data.forEach((key, value) -> {
            String outputPath = buildSavePath(path, baseFileName, String.valueOf(key),"txt");
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath))) {
                value.forEach(item->{
                    String line = String.format("%s,%s,%s%n", item.getLatString(), item.getLonString(), item.getDataString());
                    try {
                        writer.write(line);
                    } catch (IOException e) {
                        throw new CommonException(CommonErrorCode.FILE_SYS_ERROR,"写入数据时出现异常");
                    }
                });
            } catch (IOException e) {
                throw new CommonException(CommonErrorCode.FILE_SYS_ERROR,"写入文件出现异常");
            }
            pathList.add(outputPath);
        });

        return pathList;
    }

}
